// 全局变量
let currentCookies = '';
let currentCourses = [];

// DOM元素
const loginForm = document.getElementById('loginForm');
const loginBtn = document.getElementById('loginBtn');
const getCoursesBtn = document.getElementById('getCoursesBtn');
const autoEvaluateBtn = document.getElementById('autoEvaluateBtn');
const resultContent = document.getElementById('resultContent');
const loadingModal = document.getElementById('loadingModal');
const loadingText = document.getElementById('loadingText');
const notification = document.getElementById('notification');

// API基础URL
const API_BASE = '/api';

// 初始化
document.addEventListener('DOMContentLoaded', function() {
    // 绑定事件监听器
    loginBtn.addEventListener('click', handleLogin);
    getCoursesBtn.addEventListener('click', handleGetCourses);
    autoEvaluateBtn.addEventListener('click', handleAutoEvaluate);
    
    // 表单验证
    const inputs = loginForm.querySelectorAll('input');
    inputs.forEach(input => {
        input.addEventListener('input', validateForm);
    });
    
    // 初始验证
    validateForm();
});

// 表单验证
function validateForm() {
    const baseUrl = document.getElementById('baseUrl').value.trim();
    const username = document.getElementById('username').value.trim();
    const password = document.getElementById('password').value.trim();
    
    const isValid = baseUrl && username && password;
    
    loginBtn.disabled = !isValid;
    autoEvaluateBtn.disabled = !isValid;
}

// 显示加载动画
function showLoading(text = '正在处理中...') {
    loadingText.textContent = text;
    loadingModal.style.display = 'block';
    document.body.style.overflow = 'hidden';
}

// 隐藏加载动画
function hideLoading() {
    loadingModal.style.display = 'none';
    document.body.style.overflow = 'auto';
}

// 显示通知
function showNotification(message, type = 'success') {
    const notificationMessage = notification.querySelector('.notification-message');
    notificationMessage.textContent = message;
    
    // 重置类名
    notification.className = 'notification';
    notification.classList.add(type);
    
    // 显示通知
    notification.classList.add('show');
    
    // 3秒后自动隐藏
    setTimeout(() => {
        notification.classList.remove('show');
    }, 3000);
}

// 添加结果项
function addResultItem(message, type = 'info', details = null) {
    // 清除空状态
    const emptyState = resultContent.querySelector('.empty-state');
    if (emptyState) {
        emptyState.remove();
    }
    
    const resultItem = document.createElement('div');
    resultItem.className = `result-item ${type}`;
    
    let content = `<strong>${message}</strong>`;
    if (details) {
        content += `<br><small>${details}</small>`;
    }
    
    resultItem.innerHTML = content;
    resultContent.appendChild(resultItem);
    
    // 滚动到最新结果
    resultItem.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
}

// 清空结果
function clearResults() {
    resultContent.innerHTML = `
        <div class="empty-state">
            <i class="fas fa-info-circle"></i>
            <p>请先填写登录信息，然后选择操作</p>
        </div>
    `;
}

// 获取表单数据
function getFormData() {
    return {
        base_url: document.getElementById('baseUrl').value.trim(),
        username: document.getElementById('username').value.trim(),
        password: document.getElementById('password').value.trim()
    };
}

// 处理登录
async function handleLogin() {
    const formData = getFormData();
    
    showLoading('正在登录教务系统...');
    clearResults();
    
    try {
        const response = await fetch(`${API_BASE}/login`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(formData)
        });
        
        const result = await response.json();
        
        if (result.success) {
            currentCookies = result.cookies;
            getCoursesBtn.disabled = false;
            
            addResultItem('登录成功！', 'success', '已获取登录凭证，可以进行后续操作');
            showNotification('登录成功！', 'success');
        } else {
            addResultItem('登录失败', 'error', result.message);
            showNotification(result.message, 'error');
        }
    } catch (error) {
        addResultItem('网络错误', 'error', '请检查网络连接或稍后重试');
        showNotification('网络连接失败', 'error');
        console.error('Login error:', error);
    } finally {
        hideLoading();
    }
}

// 处理获取课程
async function handleGetCourses() {
    if (!currentCookies) {
        showNotification('请先登录', 'warning');
        return;
    }
    
    const formData = getFormData();
    
    showLoading('正在获取课程列表...');
    
    try {
        const response = await fetch(`${API_BASE}/get_courses`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                base_url: formData.base_url,
                cookies: currentCookies
            })
        });
        
        const result = await response.json();
        
        if (result.success) {
            currentCourses = result.courses;
            
            addResultItem(
                `课程获取成功！`, 
                'success', 
                `共找到 ${result.course_count} 门待评价课程`
            );
            showNotification(`获取到 ${result.course_count} 门课程`, 'success');
        } else {
            addResultItem('获取课程失败', 'error', result.message);
            showNotification(result.message, 'error');
        }
    } catch (error) {
        addResultItem('网络错误', 'error', '获取课程列表时发生错误');
        showNotification('获取课程失败', 'error');
        console.error('Get courses error:', error);
    } finally {
        hideLoading();
    }
}

// 处理一键评教
async function handleAutoEvaluate() {
    const formData = getFormData();
    
    // 确认对话框
    if (!confirm('确定要进行一键评教吗？\n\n此操作将自动登录并为所有待评价课程提交评价。')) {
        return;
    }
    
    showLoading('正在执行一键评教...');
    clearResults();
    
    try {
        // 添加进度提示
        addResultItem('开始一键评教流程', 'info', '正在登录系统...');
        
        const response = await fetch(`${API_BASE}/auto_evaluate`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(formData)
        });
        
        const result = await response.json();
        
        if (result.success) {
            addResultItem('一键评教完成！', 'success', result.message);
            addResultItem(
                '评教统计', 
                'info', 
                `总课程数: ${result.course_count}，成功评价: ${result.success_count}`
            );
            
            showNotification('一键评教完成！', 'success');
            
            // 更新按钮状态
            currentCookies = 'auto_login_completed';
            getCoursesBtn.disabled = false;
        } else {
            addResultItem('一键评教失败', 'error', result.message);
            showNotification(result.message, 'error');
        }
    } catch (error) {
        addResultItem('网络错误', 'error', '一键评教过程中发生错误');
        showNotification('一键评教失败', 'error');
        console.error('Auto evaluate error:', error);
    } finally {
        hideLoading();
    }
}

// 工具函数：格式化时间
function formatTime(date) {
    return date.toLocaleTimeString('zh-CN', {
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
    });
}

// 工具函数：验证URL格式
function isValidUrl(string) {
    try {
        new URL(string);
        return true;
    } catch (_) {
        return false;
    }
}

// 添加输入验证
document.getElementById('baseUrl').addEventListener('blur', function() {
    const url = this.value.trim();
    if (url && !isValidUrl(url)) {
        showNotification('请输入有效的URL地址', 'warning');
        this.focus();
    }
});

// 添加回车键支持
loginForm.addEventListener('keypress', function(e) {
    if (e.key === 'Enter') {
        e.preventDefault();
        if (!loginBtn.disabled) {
            handleLogin();
        }
    }
});

// 页面可见性变化处理
document.addEventListener('visibilitychange', function() {
    if (document.hidden) {
        // 页面隐藏时暂停动画
        document.body.classList.add('paused');
    } else {
        // 页面显示时恢复动画
        document.body.classList.remove('paused');
    }
});

// 错误处理
window.addEventListener('error', function(e) {
    console.error('Global error:', e.error);
    showNotification('页面发生错误，请刷新重试', 'error');
});

// 网络状态监听
window.addEventListener('online', function() {
    showNotification('网络连接已恢复', 'success');
});

window.addEventListener('offline', function() {
    showNotification('网络连接已断开', 'warning');
});

